"use strict";

const { User } = require("../schemas");
const { FLayout, FUtil } = require("../util");
const FError = require("../util/FError");
const { userProxy } = require("../proxy");

exports.postAdmin = async ctx => {
  const req = ctx.request;
  const reqBody = FUtil.reqVerify(req.body, User.postAdmin);
  if (!reqBody) ctx.throw(400, FError.InvalidParameters("invalid parameters"));
  const admin = await userProxy.generateAdmin(reqBody);
  if (!admin) ctx.throw(403, FError.AuthenticationRole("admin has existed"));
  FLayout.layout(null, ctx, admin);
};

exports.userLogin = async ctx => {
  const req = ctx.request;
  const reqBody = FUtil.reqVerify(req.body, User.postAdmin);
  if (!reqBody) ctx.throw(400, FError.InvalidParameters("invalid parameters"));
  const user = await userProxy.validateLogin(reqBody);
  FLayout.layout(null, ctx, { user });
};

exports.updatePass = async ctx => {
  const req = ctx.request;
  const reqBody = FUtil.reqVerify(req.body, User.updatePass);
  if (!reqBody) ctx.throw(400, FError.InvalidParameters("invalid parameters"));
  const { newPass, repeatPass } = reqBody;
  if (newPass !== repeatPass)
    ctx.throw(400, FError.InvalidParameters("two inconsistent passwords"));
  await userProxy.updatePassword(reqBody);
  FLayout.layout(null, ctx);
};
